﻿using DbMapper.controller;
using DbMapper.model;
using Microsoft.Win32;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using System.Runtime.Serialization.Json;
using System.Text;
using System.Threading.Tasks;
using System.Web.Script.Serialization;
using System.Windows.Forms;

namespace DbMapper.view {
    public partial class MainWindow : Form {

        #region  设置弹窗自动关闭，不清楚为什么这么设置
        [DllImport("user32.dll", EntryPoint = "FindWindow", CharSet = CharSet.Auto)]
        private extern static IntPtr FindWindow(string lpClassName, string lpWindowName);
        [DllImport("user32.dll", CharSet = CharSet.Auto)]
        public static extern int PostMessage(IntPtr hWnd, int msg, IntPtr wParam, IntPtr lParam);
        public const int WM_CLOSE = 0x10;
        #endregion

        TabPage tabPage;
        RichTextBox richtextbox;
        System.Timers.Timer myTimer;
        static string sqlitestring = "";
        service.SQLHelper sqlHelper = new service.SQLHelper();

        service.SQLiteDBHelper sqllitehelper = new service.SQLiteDBHelper(sqlitestring);

        MainWindowController mainWindowController = new MainWindowController();



        public MainWindow() {
            InitializeComponent();
        }

        #region //页面加载
        private void MainWindow_Load(object sender, EventArgs e) {


            int pagenumber = 0;

            // 读取规则
            string path = AppDomain.CurrentDomain.BaseDirectory + "mapper.txt";
            string path2 = AppDomain.CurrentDomain.BaseDirectory + "reocrd.txt";
            //第一步读取配置文件

            FileStream file = new FileStream(path, FileMode.Open);
            StreamReader sr = new StreamReader(file, Encoding.UTF8);
            string strLine = sr.ReadToEnd();
            // 关闭文件
            sr.Close();
            file.Close();

            List<Record> recordlist = new List<Record>();
            FileStream file2 = new FileStream(path2, FileMode.Open);
            StreamReader sr2 = new StreamReader(file2, Encoding.UTF8);
            string strLine2 = sr2.ReadToEnd();
            // 关闭文件
            sr2.Close();
            file2.Close();
            //页面加载时：讲规则赋值到页面上
            foreach (TabPage page in tabControls.TabPages) {
                foreach (Control control in page.Controls) {
                    pagenumber++;
                    if (control is RichTextBox && pagenumber == 1) {

                        ((RichTextBox)control).Text = strLine;

                    } else {
                        ((RichTextBox)control).Text = strLine2;
                    }
                }
            }

            myTimer = new System.Timers.Timer(2000);//定时周期2秒
            myTimer.Elapsed += ImportData;//到2秒了做的事件
            myTimer.AutoReset = true; //是否不断重复定时器操作
            btn_close.Visible = false;

            // btn_Import_Click(null, null);







        }
        #endregion

        #region //点击开始按钮，创建定时器。
        private void btn_Import_Click(object sender, EventArgs e) {
            ImportData(null, null);

            //var inputtimevalue = tb_inputtime.Text.Trim();

            //int timevalue = Convert.ToInt32(inputtimevalue);

            //int originvalue = timevalue * 1000;

            //myTimer = new System.Timers.Timer(originvalue);//定时周期2秒
            //myTimer.Elapsed += ImportData;//到2秒了做的事件
            //myTimer.AutoReset = true; //是否不断重复定时器操作
            //btn_close.Visible = false;
            //myTimer.Enabled = true; //定时器开始用
            //                        //如果不写下面这句会有一个异常。
            //                        //异常：线程间操作无效: 从不是创建控件"richtextbox"的线程访问它
            //                        //但这不是最好的方法。如果只有一个进程调用richtextbox而已。就可以用下面这句
            //                        //如果有多个线程调用richtextbox等控件。就要用委托。具体百度
            //                        //一篇参考博客http://www.cnblogs.com/zyh-nhy/archive/2008/01/28/1056194.html
            //Control.CheckForIllegalCrossThreadCalls = false;
            //btn_Import.Visible = false;
            //btn_close.Visible = true;

        }
        #endregion

        #region//获取用户输入的匹配规则，转化成mapper,导入。
        public void ImportData(object sender, System.Timers.ElapsedEventArgs e) {
            #region   SQLSERVER 对SQLSERVER 版本
            string path = AppDomain.CurrentDomain.BaseDirectory + "mapper.txt";
            string path2 = AppDomain.CurrentDomain.BaseDirectory + "reocrd.txt";
            //第一步读取配置文件
            FileStream file = new FileStream(path, FileMode.Open);
            StreamReader sr = new StreamReader(file, Encoding.UTF8);
            string strLine = sr.ReadToEnd();
            // 关闭文件
            sr.Close();
            file.Close();

            List<Record> recordlist = new List<Record>();
            FileStream file2 = new FileStream(path2, FileMode.Open);
            StreamReader sr2 = new StreamReader(file2);
            string strLine2 = sr2.ReadToEnd();
            // 关闭文件
            sr2.Close();
            file2.Close();
            //第二部 json文件转换成model

            try {
                List<Mapper> mapperlist = new List<Mapper>();
                mapperlist = JsonstringtoList(strLine);
                recordlist = JsonstringtoList2(strLine2);
                if (mapperlist.Count != 0) {
                    StartMapping(mapperlist, recordlist);
                    //foreach (var map in mapperlist) {
                    //    foreach (var item in recordlist) {
                    //        StartMapping(map, item);
                    //    }

                        var jsonstr = toJson(recordlist);
                        CreateFile(jsonstr);
                   // }
                }
                StartKiller();
                //第三部保存配置文件
                MessageBox.Show("导入成功", "MessageBox");


            } catch (Exception err) {
                MessageBox.Show("" + err, "MessageBox");
            }

            #endregion



        }
        #endregion

        public void StartMapping2(Mapper mapper, Record record, string tableName) {

            try {
                if (mapper.SourceTable.Name == "_") {
                    tableName = "_" + tableName;
                    DateTime now = DateTime.Now;

                    //源数据表
                    string sourcetabelname = mapper.SourceTable.Name;

                    string targertablename = mapper.TargetTable.Name;


                    List<Field> soucrefield = new List<Field>();
                    List<Field> targidfiled = new List<Field>();

                    List<int> FildKey = new List<int>();
                    if (mapper.TargetTable.Fields.Count != 0) {
                        foreach (var item in mapper.TargetTable.Fields) {
                            FildKey.Add(item.Key);
                        }
                    }

                    foreach (var item in mapper.SourceTable.Fields) {
                        if (FildKey.Contains(item.Key)) {
                            soucrefield.Add(item);

                            foreach (var item2 in mapper.TargetTable.Fields) {
                                if (item2.Key == item.Key) {
                                    targidfiled.Add(item2);
                                    break;
                                }
                            }

                        }
                    }

                    string constr = "Data Source=" + mapper.SourcePath + "; Pooling=true;FailIfMissing=false";

                    int num1 = soucrefield.Count;
                    DataTable dt2 = new DataTable();


                    DataTable dt = sqllitehelper.getTABLE("SELECT*FROM " + tableName, constr);


                    mainWindowController.ConnecteDatabase(mapper.TargetDb);//连接目标数据库
                    dt2 = mainWindowController.GetFieldDataTable(mapper.TargetTable.Name);



                    if (this.targerDbGroup.Table.Name != null) {
                        int queryNumber=0;
                        int tablenameresult = checkExitTableRcord(record.TableRecords, tableName);
                        if(tablenameresult==1) {
                          foreach(  var item   in record.TableRecords) {
                                if(item.TableName==tableName) {
                                    queryNumber =item.RecordNumber;
                                }
                            }


                        } else {
                            TableRecord model = new TableRecord();

                            model.TableName = tableName;

                            model.RecordNumber = 0;
                            record.TableRecords.Add(model);
                        }




                   
                        if (queryNumber == 0) {
                            queryNumber = 0;
                        } else {
                            queryNumber =+ 1;
                        }




                        for (int i = queryNumber; i < dt.Rows.Count; i++) {
                            bool insertresult = false;

                            string tablestring2 = GetInsertSql(targidfiled);

                            if (mapper.DefaultValue.Count != 0) {
                                for (int dv = 0; dv < mapper.DefaultValue.Count; dv++) {

                                    tablestring2 += "," + mapper.DefaultValue[dv].Name;

                                }
                            }


                            string dataname = "";
                            for (int j = 0; j < num1; j++) {
                                string sourcevalue = soucrefield[j].Name;

                                if (j == 0) {

                                    dataname += string.Format("'{0}'", dt.Rows[i][sourcevalue]);
                                } else {
                                    dataname += string.Format("," + "'{0}'", dt.Rows[i][sourcevalue]);
                                }

                            }

                            //拼接后面的值
                            if (mapper.DefaultValue.Count != 0) {
                                for (int dv2 = 0; dv2 < mapper.DefaultValue.Count; dv2++) {

                                    dataname += "," + "'" + mapper.DefaultValue[dv2].DefaultValue + "'";

                                }
                            }


                            var seqnumber = sqlHelper.GetMaxNumber("select max(SEQNO) as SEQNO from RESULTS_HEADER where BARCODE=" + "'" + dt.Rows[i]["recordID"] + "'", "Data Source=" + mapper.TargetDb.Host + " ;Initial Catalog=" + mapper.TargetDb.Name + ";User ID=" + mapper.TargetDb.User + ";Password=" + mapper.TargetDb.Password + "");
                            if (seqnumber is DBNull) {
                                insertresult = false;
                            } else {
                                int seqnumber2 = Convert.ToInt32(seqnumber);
                                var MPTHeadResult = sqlHelper.CheckBarCode("if exists(select * from  MPT_RESULTS_HEADER where RESULTS_SEQNO='" + seqnumber2 + "') select '1' else select '0'  ", "Data Source=" + mapper.TargetDb.Host + " ;Initial Catalog=" + mapper.TargetDb.Name + ";User ID=" + mapper.TargetDb.User + ";Password=" + mapper.TargetDb.Password + "");
                                if (Convert.ToInt32(MPTHeadResult) == 1) {


                                } else {
                                    //head result 中不存在该记录就添加

                                    string MPTinsertStr = "INSERT INTO MPT_RESULTS_HEADER([RESULTS_SEQNO], [BOXNUMBER], [PROFILE_ID], [PROFILE_HISTORY_ID], [AMBIENT_MODULE_ID], [AMBIENT_PROFILE_ID], [AMBIENT], [AMBIENT_UNIT], [SW_VERSION], [SERVER]) VALUES('" + seqnumber + "', '2', '9', '234', NULL, NULL, NULL, NULL, '142', '0')";

                                    sqlHelper.ExecuteSql(MPTinsertStr, "Data Source=" + mapper.TargetDb.Host + " ;Initial Catalog=" + mapper.TargetDb.Name + ";User ID=" + mapper.TargetDb.User + ";Password=" + mapper.TargetDb.Password + "");
                                }

                                DateTime time1 = Convert.ToDateTime(dt.Rows[i]["时间"]);
                                int time2 = DateTimeToStamp(time1);
                                insertresult = true;
                                tablestring2 += "," + "RESULTS_SEQNO" + "," + "TIME_STAMP" + "," + "TIME_TICK";

                                var TickNumber = sqlHelper.GetMaxNumber("select max(TIME_STAMP) as TIME_STAMP from MPT_RESULTS_SAMPLES where RESULTS_SEQNO=" + "'" +seqnumber2 + "'"+ "and TIME_TICK=0" , "Data Source=" + mapper.TargetDb.Host + " ;Initial Catalog=" + mapper.TargetDb.Name + ";User ID=" + mapper.TargetDb.User + ";Password=" + mapper.TargetDb.Password + "");

                                if(TickNumber is DBNull) {
                                    dataname += "," + "'" + seqnumber2 + "'" + "," + time2 + "," + "0";
                                    insertresult = true;
                                } else {

                                    int ticknumber = time2 - Convert.ToInt32(TickNumber);


                                    dataname += "," + "'" + seqnumber2 + "'" + "," + time2 + "," + ticknumber;
                                    insertresult = true;
                                }




                              
                            }

                            //存在就添加
                            if (insertresult) {
                                string sqlstr = string.Format("insert into {0} ({1}) values({2})", targertablename, tablestring2, dataname);
                                //存在就不往   MPT_RESULTS_HEADER  表中添加数据
                                sqlHelper.ExecuteSql(sqlstr, "Data Source=" + mapper.TargetDb.Host + " ;Initial Catalog=" + mapper.TargetDb.Name + ";User ID=" + mapper.TargetDb.User + ";Password=" +
    mapper.TargetDb.Password + "");
                                foreach (var item in record.TableRecords) {
                                    if (item.TableName == tableName) {
                                        item.RecordNumber = dt.Rows.Count;
                                    }
                                }
                            }

                        }
                    }
                }
            } catch (Exception error) {
                StartKiller();
                MessageBox.Show("" + error, "MessageBOX");
            }

        }

        #region 开始根据匹配规则导入数据库
        public void StartMapping( List<Mapper> mapperlist, List<Record> recordlist) {
            try {
                
                DateTime now = DateTime.Now;

                //源数据表
                string sourcetabelname = mapperlist[0].SourceTable.Name;

                string targertablename = mapperlist[0].TargetTable.Name;


                List<Field> soucrefield = new List<Field>();
                List<Field> targidfiled = new List<Field>();

                List<int> FildKey = new List<int>();
                if (mapperlist[0].TargetTable.Fields.Count != 0) {
                    foreach (var item in mapperlist[0].TargetTable.Fields) {
                        FildKey.Add(item.Key);
                    }
                }

                foreach (var item in mapperlist[0].SourceTable.Fields) {
                    if (FildKey.Contains(item.Key)) {
                        soucrefield.Add(item);

                        foreach (var item2 in mapperlist[0].TargetTable.Fields) {
                            if (item2.Key == item.Key) {
                                targidfiled.Add(item2);
                                break;
                            }
                        }

                    }
                }

                string constr = "Data Source=" + mapperlist[0].SourcePath + "; Pooling=true;FailIfMissing=false";

                int num1 = soucrefield.Count;
                DataTable dt2 = new DataTable();


                DataTable dt = sqllitehelper.getTABLE("SELECT*FROM " + mapperlist[0].SourceTable.Name, constr);


                mainWindowController.ConnecteDatabase(mapperlist[0].TargetDb);//连接目标数据库
                dt2 = mainWindowController.GetFieldDataTable(mapperlist[0].TargetTable.Name);



                if (this.targerDbGroup.Table.Name != null) {
                    int queryNumber;
                    if (recordlist[0].TableRecords[0].RecordNumber == 0) {
                        queryNumber = 0;
                    } else {
                        queryNumber = recordlist[0].TableRecords[0].RecordNumber + 1;
                    }




                    for (int i = queryNumber; i < dt.Rows.Count; i++) {


                        string tablestring2 = GetInsertSql(targidfiled);

                        if (mapperlist[0].DefaultValue.Count != 0) {
                            for (int dv = 0; dv < mapperlist[0].DefaultValue.Count; dv++) {

                                tablestring2 += "," + mapperlist[0].DefaultValue[dv].Name;

                            }
                        }
                        tablestring2 += "," + "FAILCODE" + "," + "SEQNO";

                        string dataname = "";
                        for (int j = 0; j < num1; j++) {
                            string sourcevalue = soucrefield[j].Name;

                            if (j == 0) {

                                dataname += string.Format("'{0}'", dt.Rows[i][sourcevalue]);
                            } else {
                                dataname += string.Format("," + "'{0}'", dt.Rows[i][sourcevalue]);
                            }

                        }

                        //拼接后面的值
                        if (mapperlist[0].DefaultValue.Count != 0) {
                            for (int dv2 = 0; dv2 < mapperlist[0].DefaultValue.Count; dv2++) {

                                dataname += "," + "'" + mapperlist[0].DefaultValue[dv2].DefaultValue + "'";

                            }
                        }


                        dataname += "," + "'" + 30001 + "'";

                        var seqnumber = sqlHelper.GetMaxNumber("select max(SEQNO) as SEQNO from RESULTS_HEADER", "Data Source=" + mapperlist[0].TargetDb.Host + " ;Initial Catalog=" + mapperlist[0].TargetDb.Name + ";User ID=" + mapperlist[0].TargetDb.User + ";Password=" + mapperlist[0].TargetDb.Password + "");
                        int seqnumber2 = Convert.ToInt32(seqnumber) + 1;
                        dataname += "," + "'" + seqnumber2 + "'";
                      

                        //查询该表中是否存在该记录
                        var result = sqlHelper.CheckBarCode("if exists(select * from  RESULTS_HEADER where BARCODE='" + dt.Rows[i][soucrefield[0].Name] + "') select '1' else select '0'  ", "Data Source=" + mapperlist[0].TargetDb.Host + " ;Initial Catalog=" + mapperlist[0].TargetDb.Name + ";User ID=" + mapperlist[0].TargetDb.User + ";Password=" + mapperlist[0].TargetDb.Password + "");


                        //存在就添加
                        if (Convert.ToInt32(result) == 1) {

                            var table2Name = "_" + dt.Rows[i]["recordID"];
                            //  StartMapping2();






                            tablestring2 = tablestring2 + "," + "MODEL_ID" + "," + "DATE_TESTED";

                            string modelID = GetModelId(dt.Rows[i][soucrefield[0].Name].ToString(), "Data Source=" + mapperlist[0].TargetDb.Host + " ;Initial Catalog=" + mapperlist[0].TargetDb.Name + ";User ID=" + mapperlist[0].TargetDb.User + ";Password=" + mapperlist[0].TargetDb.Password + "");

                            dataname = dataname + "," + "'" + modelID + "'" + "," + "'" + DateTime.Now + "'";




                            string sqlstr = string.Format("insert into {0} ({1}) values({2})", targertablename, tablestring2, dataname);

                            sqlHelper.ExecuteSql(sqlstr, "Data Source=" + mapperlist[0].TargetDb.Host + " ;Initial Catalog=" + mapperlist[0].TargetDb.Name + ";User ID=" + mapperlist[0].TargetDb.User + ";Password=" + mapperlist[0].TargetDb.Password + "");

                            recordlist[0].TableRecords[0].RecordNumber = dt.Rows.Count;
                            StartMapping2(mapperlist[1], recordlist[1], dt.Rows[i]["recordID"].ToString());
                        } else {
                            //StartKiller();
                            //MessageBox.Show("PLIS中不存在该Barcode:" + dt.Rows[0][soucrefield[0].Name], "MessageBox");
                        }
                   
                    }
                }

            } catch (Exception error) {
                StartKiller();
                MessageBox.Show("" + error, "MessageBOX");
            }

        }
        #endregion

        #region //得到目标数据表中的要插入的字段
        public string GetInsertSql(List<Field> FildList) {
            string s = "";

            if (FildList.Count != 0) {
                for (int i = 0; i < FildList.Count; i++) {
                    if (i == 0) {
                        s += FildList[i].Name;
                    } else {
                        s += "," + FildList[i].Name;
                    }
                }
            }

            return s;
        }
        #endregion


        #region //得到Update SQL 语句
        public string UpdateString() {
            string sql = "";

            return sql;

        }
        #endregion

        #region //将json 数据转换成model
        public List<Mapper> JsonstringtoList(string jsonstr) {
            JavaScriptSerializer Serializer = new JavaScriptSerializer();
            var objs = Serializer.Deserialize<List<Mapper>>(jsonstr);
            return objs;
        }
        public List<Record> JsonstringtoList2(string jsonstr) {
            JavaScriptSerializer Serializer = new JavaScriptSerializer();
            var objs = Serializer.Deserialize<List<Record>>(jsonstr);
            return objs;
        }
        #endregion

        #region//暂停定时器
        //private void btn_push_Click(object sender, EventArgs e)
        //{
        //    if (myTimer.Enabled)
        //    {
        //        myTimer.Enabled = false; //定时器停止
        //        btn_push.Text = "继续";
        //    }
        //    else
        //    {
        //        myTimer.Enabled = true;
        //        btn_push.Text = "暂停";
        //    }
        //}
        #endregion

        #region //点击关闭定时器
        private void btn_close_Click(object sender, EventArgs e) {
            myTimer.Close(); //释放Timer占用的资源
            myTimer.Dispose();
            btn_Import.Visible = true;
            btn_close.Visible = false;
            foreach (TabPage page in tabControls.TabPages) {
                foreach (Control control in page.Controls) {
                    if (control is RichTextBox) {
                        ((RichTextBox)control).ReadOnly = false;

                    }
                }
            }
        }
        #endregion

        #region  //定时器输入格式限制
        private void tb_inputtime_KeyPress(object sender, KeyPressEventArgs e) {
            if (!(Char.IsNumber(e.KeyChar)) && e.KeyChar != (char)8) {
                e.Handled = true;//经过判断为数字，可以输入
            }

        }
        #endregion


        //保存修改后规则
        private void btn_addPage_Click(object sender, EventArgs e) {
            int pagenumber = 0;
            foreach (TabPage page in tabControls.TabPages) {
                foreach (Control control in page.Controls) {
                    pagenumber++;
                    if (control is RichTextBox && pagenumber == 1) {

                        string value = ((RichTextBox)control).Text;
                        CreateFile2(value);

                    } else {

                        string value = ((RichTextBox)control).Text;
                        CreateFile(value);

                    }
                }
            }
            StartKiller();
            MessageBox.Show("保存成功", "MessageBox");
        }





        //List 转换成json
        public string toJson(List<Record> recordlist) {
            DataContractJsonSerializer json = new DataContractJsonSerializer(recordlist.GetType()); //获取数据类型
            string jsonStr = "";
            using (MemoryStream stream = new MemoryStream()) {
                json.WriteObject(stream, recordlist);
                jsonStr = Encoding.UTF8.GetString(stream.ToArray());
            }
            return jsonStr;
        }


        //讲JSON文件保存到TXT
        public void CreateFile(string jsonstring) {
            string path = AppDomain.CurrentDomain.BaseDirectory + "reocrd.txt";
            FileStream fs = new FileStream(path, FileMode.OpenOrCreate, FileAccess.ReadWrite); //可以指定盘符，也可以指定任意文件名，还可以为word等文件
            StreamWriter sw = new StreamWriter(fs, Encoding.UTF8); // 创建写入流
            fs.SetLength(0);
            sw.WriteLine(jsonstring); // 写入Hello World
            sw.Close(); //关闭文件
        }

        public void CreateFile2(string jsonstring) {
            string path = AppDomain.CurrentDomain.BaseDirectory + "mapper.txt";

            FileStream fs = new FileStream(path, FileMode.OpenOrCreate, FileAccess.ReadWrite); //可以指定盘符，也可以指定任意文件名，还可以为word等文件
            fs.SetLength(0);
            StreamWriter sw = new StreamWriter(fs, Encoding.UTF8); // 创建写入流
            sw.WriteLine(jsonstring); // 写入Hello World
            sw.Close(); //关闭文件
        }

        private void ckBox_CheckedChanged(object sender, EventArgs e) {
            if (ckBox.Checked) {
                StartKiller();
                MessageBox.Show("设置开机自启动，需要修改注册表", "MessageBox");
                string path = Application.ExecutablePath;
                RegistryKey rk = Registry.CurrentUser;
                RegistryKey rk2 = rk.CreateSubKey(@"Software\Microsoft\Windows\CurrentVersion\Run");
                rk2.SetValue("JcShutdown", path);
                rk2.Close();
                rk.Close();
            } else {
                StartKiller();
                MessageBox.Show("取消开机自启动，需要修改注册表", "MessageBox");
                string path = Application.ExecutablePath;
                RegistryKey rk = Registry.CurrentUser;
                RegistryKey rk2 = rk.CreateSubKey(@"Software\Microsoft\Windows\CurrentVersion\Run");
                rk2.DeleteValue("JcShutdown", false);
                rk2.Close();
                rk.Close();
            }
        }

        //private void checkBox1_CheckedChanged(object sender, EventArgs e) {

        //    if (checkBox1.Checked) //设置开机自启动  
        //                {
        //        MessageBox.Show("设置开机自启动，需要修改注册表", "提示");
        //        string path = Application.ExecutablePath;
        //        RegistryKey rk = Registry.CurrentUser;
        //        RegistryKey rk2 = rk.CreateSubKey(@"Software\Microsoft\Windows\CurrentVersion\Run");
        //        rk2.SetValue("JcShutdown", path);
        //        rk2.Close();
        //        rk.Close();
        //    } else //取消开机自启动  
        //      {
        //        MessageBox.Show("取消开机自启动，需要修改注册表", "提示");
        //        string path = Application.ExecutablePath;
        //        RegistryKey rk = Registry.CurrentUser;
        //        RegistryKey rk2 = rk.CreateSubKey(@"Software\Microsoft\Windows\CurrentVersion\Run");
        //        rk2.DeleteValue("JcShutdown", false);
        //        rk2.Close();
        //        rk.Close();
        //    }

        //}


        private void StartKiller() {
            Timer timer = new Timer();
            timer.Interval = 3000; //3秒启动 
            timer.Tick += new EventHandler(Timer_Tick);
            timer.Start();
        }
        private void Timer_Tick(object sender, EventArgs e) {
            KillMessageBox();
            //停止Timer 
            ((Timer)sender).Stop();
        }
        private void KillMessageBox() {
            //按照MessageBox的标题，找到MessageBox的窗口 
            IntPtr ptr = FindWindow(null, "MessageBox");
            if (ptr != IntPtr.Zero) {
                //找到则关闭MessageBox窗口 
                PostMessage(ptr, WM_CLOSE, IntPtr.Zero, IntPtr.Zero);
            }
        }
        //返回modeId
        public string GetModelId(string barcode, string strcon) {
            string sql = "SELECT  MODEL_ID FROM RESULTS_HEADER WHERE  BARCODE = '" + barcode + "'";

            DataTable dt = sqlHelper.GetModelIDTable(sql, strcon);
            if (dt.Rows.Count == 0) {
                MessageBox.Show(barcode);
            }

            return dt.Rows[0]["Model_ID"].ToString();

        }


        // DateTime时间格式转换为Unix时间戳格式
        private int DateTimeToStamp(System.DateTime time) {
            System.DateTime startTime = TimeZone.CurrentTimeZone.ToLocalTime(new System.DateTime(1970, 1, 1));
            return (int)(time - startTime).TotalSeconds;
        }


        public int  checkExitTableRcord(List<TableRecord>list, string tableName) {
            int i = 0;
            foreach(var item in list) {
                if (item.TableName == tableName) {
                    i++;
                }
                         
            }

            if(i==0) { return 0; }
            else {
                return 1;
            }
            
        }

    }
}


